<?php

namespace app\admin\model\article;

use think\Model;


class Article extends Model
{





    // 表名
    protected $name = 'article';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    const TYPE_ORDINARY = 1; // 普通文章
    const TYPE_SYSTEM = 2; // 系统
    const TYPE_MESSAGE = 100; // 公告消息
    const TYPE_BUY_VIP = 101; // 购买VIP



    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }









    public function articlecategory()
    {
        return $this->belongsTo('app\admin\model\article\Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 获取列表
     * @param object $user 用户
     */
    public function getList($condition = [],$user = null){
        $articleSeeModel = new ArticleSee();
        $list = self::where($condition)->where("switch", 1)->field("id, title, image,type")->order("weigh", "desc")->paginate();
        foreach ($list as $key => $value) {
            $value["image"] =  deal_img_url($value["image"]);
            $value["is_see"] =  $articleSeeModel->checkSee($value["id"],  $value["type"], $user);
        }
        return $list;
    }

    /**
     * 获取详情
     * @param object $user 用户
     *
     */
    public function getInfo($condition = [],$user = null) {
        $info = self::where($condition)->where("switch", 1)->find();
        if(!$info){
            exception("未找到该文章");
        }
        $info["image"] = deal_img_url($info["image"]);
        $info["createtime"] = date("Y-m-d H:i:s", $info["createtime"]);
        //检测是否已读  未读的话 加一条记录
        $articleSeeModel = new ArticleSee();
        if(!$articleSeeModel->checkSee($info["id"], $info["type"], $user)){
            $articleSeeModel->addSee($info,$info["type"],$user);
        }
        return $info;
    }
}
